#include "BluePrintView.h"
#include <QGraphicsScene>
#include <QPainter>
#include <QContextMenuEvent>
#include <QMenu>
#include <QAction>
#include <QGraphicsRectItem>
#include <QGraphicsTextItem>
#include <QBrush>
#include <QPen>
#include <cmath>
#include <QDebug>

BluePrintView::BluePrintView(QWidget *parent)
    : QGraphicsView(parent)
{
    // 移除场景创建 - 现在由Controller管理
    // QGraphicsScene *scene = new QGraphicsScene(this);
    // scene->setSceneRect(-5000, -5000, 10000, 10000);
    // setScene(scene);

    // View层只负责视图的配置
    setRenderHint(QPainter::Antialiasing);
    setDragMode(QGraphicsView::NoDrag);
    setTransformationAnchor(QGraphicsView::AnchorUnderMouse);
    setResizeAnchor(QGraphicsView::AnchorUnderMouse);
    setBackgroundBrush(QColor(40, 40, 48));
    setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    // 创建右键菜单
    createContextMenu();
}

void BluePrintView::wheelEvent(QWheelEvent *event)
{
    double scaleFactor = 1.15;
    if (event->angleDelta().y() > 0) {
        scale(scaleFactor, scaleFactor);
    } else {
        scale(1.0 / scaleFactor, 1.0 / scaleFactor);
    }
}

void BluePrintView::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        // 检查是否点击到了节点
        QGraphicsItem *item = itemAt(event->pos());
        
        if (item) {
            // 如果点击到节点，完全交给节点处理，不处理画布拖拽
            QGraphicsView::mousePressEvent(event);
            return;
        } else {
            // 如果点击到空白区域，处理画布拖拽
            m_isDragging = true;
            m_mousePressPos = event->pos();
            m_sceneCenterOnPress = mapToScene(viewport()->rect().center());
            setCursor(Qt::ClosedHandCursor);
            event->accept();
            return;
        }
    }
    QGraphicsView::mousePressEvent(event);
}

void BluePrintView::mouseMoveEvent(QMouseEvent *event)
{
    if (m_isDragging && event->buttons() & Qt::LeftButton) {
        // 修复：只有在画布拖拽模式下才处理画布拖拽
        // 不再检查当前鼠标位置下的item，因为那会干扰判断
        QPointF delta = event->pos() - m_mousePressPos;
        QPointF sceneDelta = delta / transform().m11();
        QPointF newCenter = m_sceneCenterOnPress - sceneDelta;
        centerOn(newCenter);
        event->accept();
        return;
    }
    QGraphicsView::mouseMoveEvent(event);
}

void BluePrintView::mouseReleaseEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton) {
        if (m_isDragging) {
            m_isDragging = false;
            setCursor(Qt::ArrowCursor);
            event->accept();
            return;
        }
    }
    QGraphicsView::mouseReleaseEvent(event);
}

void BluePrintView::drawBackground(QPainter *painter, const QRectF &rect)
{
    painter->fillRect(rect, QColor(40, 40, 40));
    QPen smallGridPen(QColor(60, 60, 70)); smallGridPen.setCosmetic(true);
    QPen largeGridPen(QColor(80, 80, 90)); largeGridPen.setCosmetic(true);

    const int smallGridSize = 20, largeGridSize = 100;
    qreal left = std::floor(rect.left()), right = std::ceil(rect.right());
    qreal top = std::floor(rect.top()), bottom = std::ceil(rect.bottom());

    painter->setPen(smallGridPen);
    for (qreal x = left - ((int)left % smallGridSize); x < right; x += smallGridSize)
        painter->drawLine(QPointF(x, top), QPointF(x, bottom));
    for (qreal y = top - ((int)top % smallGridSize); y < bottom; y += smallGridSize)
        painter->drawLine(QPointF(left, y), QPointF(right, y));

    painter->setPen(largeGridPen);
    for (qreal x = left - ((int)left % largeGridSize); x < right; x += largeGridSize)
        painter->drawLine(QPointF(x, top), QPointF(x, bottom));
    for (qreal y = top - ((int)top % largeGridSize); y < right; y += largeGridSize)
        painter->drawLine(QPointF(left, y), QPointF(right, y));

    QPen originPen(Qt::red, 2); originPen.setCosmetic(true);
    painter->setPen(originPen);
    painter->drawLine(QPointF(-10, 0), QPointF(10, 0));
    painter->drawLine(QPointF(0, -10), QPointF(0, 10));
}

void BluePrintView::createContextMenu()
{
    // 创建右键菜单
    m_contextMenu = new QMenu(this);

    // 创建 菜单项
    QAction *addNodeAction = new QAction("添加加法节点", this);
    connect(addNodeAction, &QAction::triggered, this, &BluePrintView::onCreateAddNode);

    m_contextMenu->addAction(addNodeAction);
}

void BluePrintView::contextMenuEvent(QContextMenuEvent *event)
{
    // 记录右键点击位置（转换为场景坐标）
    m_lastRightClickPos = mapToScene(event->pos());
    
    // 显示右键菜单
    if (m_contextMenu) {
        m_contextMenu->exec(event->globalPos());
    }
    
    event->accept();
}

void BluePrintView::onCreateAddNode()
{
    // 发出创建加法节点的信号，让Controller处理具体的创建逻辑
    emit requestCreateNode("AddNode", m_lastRightClickPos);
}